﻿#region Creditos

/* Autor: Edilberto Sánchez Forero	*/
/* Email: esanchezfo@gmail.com		*/
/* Licencia: LGPL, Software Libre	*/
/* País: Colombia, Bogotá			*/

#endregion

#region Librerias

using System.Collections.Generic;
using System.Net;
using Ciatel.ISO8583.Amex;
using Ciatel.ISO8583.Amex.Utilities;
using ESF.General;
using ESF.SSO.Core.Entities;
using System;
using ESF.SSO.Core.Entities.Log;
using ESF.SSO.Core.Entities.Exceptions;
using ESF.General.Entity;
using System.ServiceModel;
using System.Net.Sockets;

#endregion


namespace ESF.SSO.ISO8583.ServerRequestHandler.Operations
{
	internal static class CloseSession
	{
		internal static void ProcessRequest (List<Message> pRequests, IPEndPoint pSenderIPEndPoint, IPEndPoint pForwarderIPEndPoint, out List<Message> pResponses, out List<object> pProcessedObjects)
		{
			Message request;
			
			CustomField customField_57;
			
			
			request = pRequests [0];
			
			request.ApplicationData.DataElements.CheckHasMandatoryFields
			(
				TheKnownFields.PrimaryAccountNumber,
				TheKnownFields.PersonalIdentificationNumberData,
				TheKnownFields.CustomPrivateField_57
			);
			
			
			customField_57 = request.ApplicationData.DataElements.GetCustomPrivateField_57 ();
			
			
			try
			{
				using (SSOServiceClient.SSOServiceClient ssoClient = new SSOServiceClient.SSOServiceClient ())
				{
					ssoClient.CloseSessionByIdentificationCredentials (
						new User () 
						{ 
							IdentificationNumber = Tools.IntArrayToString (request.ApplicationData.DataElements.GetPrimaryAccountNumber ()).Replace (SSORequestHandler.Client_BIN, string.Empty),
							IdentificationType = new BasicReference () { ID = 1 },
							Password = request.ApplicationData.DataElements.GetPersonalIdentificationNumberDataAsString (SSORequestHandler.PASSWORD_LENGTH),
							UserTerminal = new Terminal () { Code = request.ApplicationData.DataElements.GetTerminalId (), UserHostAddress = pSenderIPEndPoint.ToString () },
							SessionID = customField_57.GetStringFieldWithVariableLength (40)	// Ans .. 40
						});
				}
					
				pResponses = new List<Message> ();
				
				pResponses.Add (request.GenerateBasicResponse (pForwarderIPEndPoint.Port));
				
				pProcessedObjects = null;
			}
			catch (FaultException gEx)
			{
				throw new GenericException (SSOExceptionCodes.ToSSOISO8583ExceptionCode (gEx.Code.Name), gEx.Message);
			}			
		}
	}
}
